<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\Category\AddSecondCategoryAction;
use App\Admin\Actions\Category\AddThirdCategoryAction;
use App\Admin\Actions\Category\CategoryDeleteAction;
use App\Admin\Actions\Category\CategoryEditAction;
use App\Admin\Grid\NGrid;
use App\Admin\Grid\Tools\Category\CategoryTools;
use App\Models\ShopCategoryModel;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Grid\Displayers\Actions;
use Encore\Admin\Grid\Tools;

class CategoryController extends AdminController
{
    protected $title = '分类管理';

    protected function grid(): NGrid
    {
        $grid = new NGrid(new ShopCategoryModel);
        $grid->model()->where('status_delete', 0);
        $grid->filter(function ($filter) {
            $filter->disableIdFilter();
            $filter->column(1 / 2, function ($filter) {
                $filter->equal('category_id', 'ID')->integer();
                $filter->ilike('category_name', __('category.category_name'));
            });
        });

        $grid->column('category_id', 'ID')->sortable();
        $grid->column('category_status', __('l.status'))->using(__('category.statusArr'));
        $grid->column('category_name', __('category.category_name'));
        $grid->column('category_level', __('category.category_level'))->display(function () {
            if (is_null($this->category_level)) return '无';
            else {
                $model = ShopCategoryModel::query()->whereIn('category_id', explode(',', $this->category_level))->pluck('category_name')->toArray();
                return implode('/', $model);
            }
        });
        $grid->column('sort', __('category.sort'))->sortable();
        $grid->column('class_img_url', '分类图片')->display(function ($column) {
            if (!is_null($column)) return view('image', ['id' => $this->product_id, 'image' => fileIdToUrl($column)]);
            else return null;
        });
        $grid->column('class_jump_url', '分类跳转地址');

        $grid->actions(function (Actions $action) {
            $action->disableEdit();
            $action->disableView();
            $action->disableDelete();
            if ($action->row->category_parent_id === 0) $action->add(new AddSecondCategoryAction);
            $categoryLLevel = explode(',', $action->row->category_level);
            if (count($categoryLLevel) === 1 && $action->row->category_parent_id > 0) $action->add(new AddThirdCategoryAction);
            $action->add(new CategoryDeleteAction);
            $action->add(new CategoryEditAction);
        });
        $grid->disableActions(false);
        $grid->disableCreateButton();
        $grid->tools(function (Tools $tools) {
            $tools->append(new CategoryTools);
        });
        return $grid;
    }
}
